const express = require('express')
const fs = require('fs')
const path = require('path')
const article = require('../db/articleSchema')
const multer = require('multer')
const router = express.Router()

/* ******************** 图片上传接口 ******************** */

// 1. 打开或创建一个名字叫folder文件夹
let createFolder = function(folder) {
  try {
      fs.accessSync(folder) // 打开文件夹
  } catch (e) {
      fs.mkdirSync(folder) // 创建文件夹
  } 
}
let uploadFolder = path.resolve(__dirname, '../static/img')
// let uploadFolder = './upload/' // 设定存储文件夹为当前目录下的 /upload 文件夹
createFolder(uploadFolder)

// 2. 设置磁盘存贮
let storage = multer.diskStorage({
  destination: function(req, file, cb) {
      cb(null, uploadFolder); // 他会放在当前目录下的 /upload 文件夹下（没有该文件夹，就新建一个）
  },
  filename: function(req, file, cb) { // 在这里设定文件名
    //file.originalname是将文件名设置为上传时的文件名，file中携带的，加上Date.now()可以避免命名重复
      cb(null, Date.now() + '-' + file.originalname)
  }
})

let upload = multer({ storage: storage })
router.post('/uploadImg',upload.array("file"), function (req, res) {
	let files = req.files
	let dataArr = files.map(i => {
		let url = '/api/public/img/' + i.filename
		 return {
			isOK: true,
			imgPath: url, //文件存储的路径
			imgName: i.filename
		}
	})
	// console.log(a)
	// var url = '/api/public/img/' + req.file.filename
    res.send({
        error:0,
        data: dataArr
    })
 })
 
/* ******************** 添加文章接口 ******************** */
router.post('/addNewArticle', (req, res) => {
	const params = req.body
	params.audit = '0'
	params.auditTime = ''
	params.note = ''
	params.using = false
	article.create(params, (err, result) => {
		if (err) {
			throw error
		} else {
			res.send({
				status: 200,
				data: {
					code: 0,
				},
				msg: '添加成功'
			})
		}
	})
})

/* ******************** 查询文章列表接口 ******************** */
router.get('/getArticleList', (req, res) => {
	const { query } = req
	let total = 0
	let currentPage = query.currentPage // 当前页
	let pageSize = query.pageSize // 每页显示数量
	let _skip = (currentPage - 1) * pageSize
	
	let artList = article.find({})
	artList.skip(_skip);  // `skip` 跳过指定数量的数据
	artList.limit(pageSize) // 限制条数，每次查多少条
	artList.exec((err, value) => {
	// 找出审核通过的文章
		if (err) {
			res.send({
				status: 500,
				msg: '查询错误'
			})
		} else {
			// 查询总数据量
			article.find((err, result) => {
				total = result.length
				res.send({
					status: 200,
					data: {
						code: 0,
						total: total, // 总页数
						articleList: [...value]
					},
					msg: '查询当前页成功'
				})
			})
		}
	})
})

/* ******************** 删除单个文章接口 ******************** */
router.post('/deletArticle', async (req, res) => {
	const { id } = req.body
    article.deleteOne({id}, (err, docs) => {
		if (err) {
			throw error
		} else {
			res.send({
				status: 200,
				data: {
					code: 0,
				},
				msg: '删除成功'
			})
		}
	})
})

router.get('/getMyArticle', (req, res) => {
	const { query } = req
	let total = 0
	let currentPage = query.currentPage // 当前页
	let pageSize = query.pageSize // 每页显示数量
	let _skip = (currentPage - 1) * pageSize

	let author  = query.author
	
	let artList = article.find({author})
	artList.skip(_skip);  // `skip` 跳过指定数量的数据
	artList.limit(pageSize) // 限制条数，每次查多少条
	artList.exec((err, value) => {
	// 找出审核通过的文章
		if (err) {
			res.send({
				status: 500,
				msg: '查询错误'
			})
		} else {
			// 查询总数据量
			article.find((err, result) => {
				total = result.length
				res.send({
					status: 200,
					data: {
						code: 0,
						total: total, // 总页数
						articleList: [...value]
					},
					msg: '查询当前页成功'
				})
			})
		}
	})
})

/* ******************** 查询单个文章接口 ******************** */
router.get('/getArticle', async (req, res) => {
	const { id } = req.query
	let art = await article.findOne({id})
	if (art) {
		res.send({
			status: 200,
			data: {
				code: 0,
				art
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询错误'
		})
	}
})

/* ******************** 查询所有文章接口 ******************** */
router.get('/getAllArticles', async (req, res) => {
	let arts = await article.find({})
	if (arts) {
		let published = 0 // 已发布
		let audit = 0 // 待审核
		for (const item of arts) {
			if (item.using === true) {
				published += 1
			} else if (item.audit === '0') {
				audit += 1
			}
		}
		res.send({
			status: 200,
			data: {
				code: 0,
				arts,
				total: arts.length,
				published,
				audit
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询错误'
		})
	}
})
/* ******************** 模糊查询 ******************** */
router.get('/fuzzyQueryArticle', async (req, res) => {
	let paramObj = req.query
	const arr = []
	for (const [key, value] of Object.entries(paramObj)) {
		if (value != '') {
			let regexp = new RegExp(paramObj[key],'i')
			const obj = {}
			obj[key] = {$regex: regexp}
			arr.push(obj)
		}
	}
    console.log(arr)
	let currentPage = paramObj.currentPage // 当前页
	let pageSize = paramObj.pageSize // 每页显示数量
	let _skip = (currentPage - 1) * pageSize
	let artList = article.find({$and: arr})
	artList.skip(_skip);  // `skip` 跳过指定数量的数据
	artList.limit(pageSize) // 限制条数，每次查多少条
	artList.exec((err, value) => {
		if (err) {
			res.send({
				status: 500,
				msg: '查询错误'
			})
		} else {
			// 查询总数据量
			article.find((err, result) => {
				res.send({
					status: 200,
					data: {
						code: 0,
						total1: value.length, // 总页数
						data: [...value]
					},
					msg: '查询当前页成功'
				})
			})
		}
	})

	// article.find({ $and: arr }, (err, doc) => {
    //     if(err){
    //         res.send({
	// 			status: 500,
	// 			msg: '查询失败'
	// 		})
    //     }
    //     if(doc){
	// 		res.send({
	// 			status: 200,
	// 			data: {
	// 				code: 0,
	// 				data: doc
	// 			},
	// 			msg: '查询成功'
	// 		})
    //     }
    // })
})

/* ******************** 修改单个文章接口（如修改：审核状态等） ******************** */
router.post('/editArticle', (req, res) => {
	const { id } = req.body
	const params = req.body
	article.findOne({id}).exec(function(err,data){
		if (data) {
			for (const [key, value] of Object.entries(params)) {
				if (key != 'id') {
					if (key === 'audit' && value === '1') {
						data['using'] = true
					}
					data[key] = value
				}
			}
			data.save(function(err){
				// err在修改错误时报错有值
				if (err) {
					res.send({
						status: 500,
						msg: '审核失败'
					})
				} else {
					res.send({
						status: 200,
						data: {
							code: 0,
						},
						msg: '审核成功'
					})
				}
			})
		}	
	})
})



/* 导出router对象 */
module.exports = router
